/**
* 创建者：lym
* 该页面用于：
* 创建时间： 2020-01-02 20:25:57
*/
import Map from "@/components/ly_components/map/Map"
import BrokenLineChart from "@/components/Charts/BrokenLineChart";
import MyVideo from "@/components/ly_components/map/MyVideo"
import { getEntInfo, getRadInfo, getGISSupervision, getGISAbnormalTrend, getRadPath, getGISDoseTrend } from "@/api/RCIM/RCIM-sourceSpace"
import { getStatus } from "@/api/RCIM/RCIM-historyTrend.js"
import {cloneDeep} from "lodash";
import moment from "moment";
import FishChart from "@/components/luyiming/FishChart/index.vue"
import { mapActions } from "vuex";
import wgs from "@/utils/gis.js"
export default {
    name: 'SourceSpace_view',
    components: {
        Map,
        BrokenLineChart,
        MyVideo,
        FishChart,
    },
    // 数据
    data() {
        return {
            hasMyOverlay: true,
            sourceSpaceInfo: {
                enterpriseInfo: { // 企业基本信息
                    enterpriseId: 1, // 企业id
                    enterprise: "", // 企业名称
                    areaName: "", // 所属区域
                    businessLicense: "", // 营业许可证
                    orgCode: "", // 组织机构代码
                    enterpriseType: "", // 企业类型
                    entNumber: "", // 编号
                    phone: "", // 电话
                    address: "", // 地址
                    chargeEnvName: "" //分管环保
                },
                originBaseInfo: { // 源基本信息
                    id: 2, // 源id
                    sourceCode: "", // 源国家编码
                    nuclideName: "", // 核素名称
                    nuclearNumber: "", //目视码
                    sourceType: "", // 源类别
                    storageState: "", // 收储状态
                    factoryActivity: "", // 出厂活度
                    factoryTime: "", // 出厂日期
                    grade: "", // 标号
                    hairWeight: "", // 毛重
                    weight: "", // 净重
                    strength: "", // 强度
                    halfTime: "", // 半衰期
                    receiptDate: "", // 接收期
                    legalPerson: "", // 法人
                    sourceUnit: "", // 产源单位名称
                    videoUrl: "", // 视频监控地址url
                },
                supervisingInformation: [ // 督办信息
                    // {
                    //     abnormalType: "异常类型", // 异常类型
                    //     abnormalDate: "****", // 异常产生时间
                    //     abnormalTotalTime: "", // 异常总时长
                    // },{
                    //     abnormalType: "异常类型", // 异常类型
                    //     abnormalDate: "****", // 异常产生时间
                    //     abnormalTotalTime: "", // 异常总时长
                    // }
                ],
                monthlyAbnormalTrend: { // 月度异常趋势图
                    monthList: [], //"6月", "7月", "8月", "9月", "10月", "11月"
                    dataList: [] // '', '', '', '', '', ''
                },
                monthlyDoseTrend: { // 月度剂量趋势图
                    monthList: [],
                    dataList: []
                },
                originStatusChange: [ // 源状态变更
                    // {
                    //     originStatusChangeId: 1, // 源状态变更id
                    //     changeDate: "***", // 变更时间
                    //     originStatus: "***", // 源状态
                    //     originNowStatus: "****", // 现状
                    //     dose: "***", // 剂量
                    // },
                    // {
                    //     originStatusChangeId: 1, // 源状态变更id
                    //     changeDate: "***", // 变更时间
                    //     originStatus: "***", // 源状态
                    //     originNowStatus: "****", // 现状
                    //     dose: "***", // 剂量
                    // }
                ],
                originMapData: { // 地图数据
                    originInfo: { // 当前源数据信息
                        point: { lng: 116.404, lat: 39.815 }, // 坐标点
                        infoWindowType: "origin", // 数据类型，
                        infoWindowInfo: {
                          originInfo: {
                              originId: 6, // 源id
                              originName: "某某源", // 源名称
                              originUse: "", // 用途
                              originType: "", // 类别
                              originCode: "", // 目视码
                              originToolCode: "", //源国家编码
                              videoUrl: "" // 视频地址url
                            },
                        }
                      },
                    polylinePath: [ // 折线上所有点数据
                        { lng: 116.46865, lat: 39.914112, },
                        { lng: 116.46865, lat: 39.877355, },
                        { lng: 116.556612, lat: 39.875583, },
                        { lng: 116.615829, lat: 39.872482, }
                    ],
                    startPoint: {
                        point: { lng: 116.46865, lat: 39.914112, }, // 起点坐标
                    },
                    endPoint: {
                        point: { lng: 116.615829, lat: 39.872482, }, // 终点坐标
                    },
                    recordPoint: [ // 记录点信息，出库，运输，作业，入库
                        {
                            recordId: 1, // 记录id
                            recordType: "checkout", // 表示出库
                            point: { lng: 116.46865, lat: 39.914112, }, // 坐标位置
                            color: "#ffb870",
                            showEffectOn: "emphasis"
                        },
                        {
                            recordId: 2, // 记录id
                            recordType: "transport", // 表示运输
                            point: { lng: 116.46865, lat: 39.877355, }, // 坐标位置
                            color: "#f43333",
                            showEffectOn: "emphasis"
                        },
                        {
                            recordId: 3, // 记录id
                            recordType: "task", // 表示作业
                            point: { lng: 116.556612, lat: 39.875583, }, // 坐标位置
                            color: "#9013fe",
                            showEffectOn: "render"
                        },
                        {
                            recordId: 4, // 记录id
                            recordType: "warehousing", // 表示入库
                            point: { lng: 116.615829, lat: 39.872482, }, // 坐标位置
                            color: "#036dfc",
                            showEffectOn: "emphasis"
                        }
                    ],
                }
            },
            EnterpriseSiteRadID: 0, // 源id
            myVideoShow: false,
            leftShow: true,
            leftButtonShow: false,
            type:{
				format: "yyyy-MM-dd HH:mm",
				precise: "datetimerange", // 精度 year/month/date/dates/ week/datetime/datetimerange/ daterange/monthrange
				longer: "30"
            },
            timmer: [],
            listQuery: {
                id: '',
                startTime: '',
                endTime: ''
            },
            chartData: {
				data: [],
				xdata: [],
				efData: [],
				vmap: []
            },
            colorList: {
				"入库": '#1890ff',
				"作业": '#a84bf9',
				"运输": '#f43333',
    			"出库": '#ffb870',
    			"在库": '#67C23A',
            },
            isClick: true,
            types: "1",
            list: [],
            dateUit: 'minute',
			useRadDeviceID: '',
			recordPoint: [
            //     {
            //     recordId: 1, // 记录id
            //     recordType: "checkout", // 表示出库
            //     point: { lng: 116.46865, lat: 39.914112, }, // 坐标位置
            //     color: "#ffb870",
            //     showEffectOn: "emphasis"
            // },
            // {
            //     recordId: 2, // 记录id
            //     recordType: "transport", // 表示运输
            //     point: { lng: 116.46865, lat: 39.877355, }, // 坐标位置
            //     color: "#f43333",
            //     showEffectOn: "emphasis"
            // },
            // {
            //     recordId: 3, // 记录id
            //     recordType: "task", // 表示作业
            //     point: { lng: 116.556612, lat: 39.875583, }, // 坐标位置
            //     color: "#9013fe",
            //     showEffectOn: "render"
            // },
            // {
            //     recordId: 4, // 记录id
            //     recordType: "warehousing", // 表示入库
            //     point: { lng: 116.615829, lat: 39.872482, }, // 坐标位置
            //     color: "#036dfc",
            //     showEffectOn: "emphasis"
            // }
            ],
			markerPointsList: [],
			sourcePoint: {},
			center: {lng: 105.000, lat: 38.000},
			selectId: '',
        }
    },
    // 监听
    watch: {

    },
    // Vue实例初始化完成
    created() {
        this.EnterpriseInfoID = this.$route.query.EnterpriseInfoID
        this.EnterpriseSiteRadID = this.$route.query.EnterpriseSiteRadID
		this.useRadDeviceID = this.$route.query.radId
		this.sourcePoint = {
			lng: this.$route.query.lng,
			lat: this.$route.query.lat,

		}
        // console.log(`源id:${this.EnterpriseSiteRadID}`)

        this.getSourceSpaceInfo()
        this.changeLeftShow()
        window.addEventListener('resize', this.changeLeftShow)
    },
    // Vue挂载完成
    mounted() {
        this.timmer = [moment().subtract(1, 'days').format('YYYY-MM-DD HH:mm'), moment().format('YYYY-MM-DD HH:mm'), ]
		this.changeDate(this.timmer)
    },
    // Vue实例销毁前
    beforeDestroy(){
        window.removeEventListener('resize', this.changeLeftShow)
    },
    // 挂载的方法
    methods: {
        /**
         * @desc 获取源轨迹数据
         * @param {Object} query 提交数据
         */
		getRadPath(query){
			return getRadPath(query).then(res => {
				this.sourceSpaceInfo.originMapData.polylinePath = res.data.polylinePath.map(item => {
					return {
						lat: item.lat - 0,
						lng: item.lng - 0
					}
				})
				this.sourceSpaceInfo.originMapData.startPoint = res.data.startPoint
				this.sourceSpaceInfo.originMapData.endPoint = res.data.endPoint
				this.recordPoint = res.data.recordPoint instanceof Object ? [res.data.recordPoint] : res.data.recordPoint;
				this.center = this.sourcePoint;
				this.markerPointsList = [
					{point: this.sourcePoint,iconUrl: {url:require("../../assets/info_images/source.png"),size:{width:46,height:46}}},
					{point: res.data.startPoint ,iconUrl: {url:require("../../assets/info_images/startPoint.png"),size:{width:46,height:46}}},
					{point: res.data.endPoint,iconUrl: {url:require("../../assets/info_images/endPoint.png"),size:{width:46,height:46}}}
				]
			})
		},
        /**
         * @desc 返回上一页
         */
        goback(){
            window.history.go(-1)
        },
        /**
         * @desc 获取源空间信息
         */
        async getSourceSpaceInfo() {
            const EnterpriseInfoID = this.EnterpriseInfoID
            const EnterpriseSiteRadID = this.EnterpriseSiteRadID
            const enterpriseInfo = await getEntInfo({id: EnterpriseInfoID})
            const originBaseInfo = await getRadInfo({id: EnterpriseSiteRadID})
            // console.log(originBaseInfo)
            const supervisingInformation = await getGISSupervision({id: EnterpriseSiteRadID})
            const monthlyAbnormalTrend = await getGISAbnormalTrend({id: EnterpriseSiteRadID})
            const sourceTrendInfo = await getGISDoseTrend({id: EnterpriseSiteRadID})
            this.sourceSpaceInfo.enterpriseInfo = enterpriseInfo.data.data
            this.sourceSpaceInfo.originBaseInfo = originBaseInfo.data.data

            // 异常督办
            this.sourceSpaceInfo.supervisingInformation = supervisingInformation.data;
            // debugger
            const dataList1 = []
            const monthList1 = []
            sourceTrendInfo.data.forEach(item => {
                dataList1.push(item.value)
                monthList1.push(item.name)
            })
            this.sourceSpaceInfo.monthlyDoseTrend = {
                dataList: dataList1,
                monthList: monthList1
            }
            // this.sourceSpaceInfo.supervisingInformation = supervisingInformation.data.map(item => {
            //     const tempTime = moment.duration(item.abnormalTotalTime,"seconds");
            //     item.abnormalTotalTime = tempTime.hours() + "小时"+ tempTime.minutes() + "分钟";
            //     return item
            // })

            // 异常趋势图
            const dataList = []
            const monthList = []
            monthlyAbnormalTrend.data.trendData.forEach(item => {
                dataList.push(item.value)
                monthList.push(moment(item.month).get('month') + 1 + "月")
            })
            this.sourceSpaceInfo.monthlyAbnormalTrend={dataList,monthList}
        },
        handleChangeRecodeId(recordId) { // 获取点击记录点，出库，运输等
			// global.alert(`recordId:${recordId}`)
            this.recordPoint.forEach(item => {
                // item.showEffectOn = "render"
                if(item.recordId == recordId) {
                    item.showEffectOn = "render"
                } else {
                    item.showEffectOn = "emphasis"
                }
            })
            this.recordPoint = cloneDeep(this.recordPoint)
            const index = this.list.findIndex(item => item.statusId == recordId)
            this.chartData = this.parseData()
            console.log(this.recordPoint)
            // console.log(this.sourceSpaceInfo.originMapData.recordPoint)
        },
        handleChangeRecodeIdFish(recordId) { // 获取点击记录点，出库，运输等
			// global.alert(`recordId:${recordId}`)
            this.recordPoint.forEach(item => {
                // item.showEffectOn = "render"
                if(item.recordId == recordId) {
                    item.showEffectOn = "render"
                } else {
                    item.showEffectOn = "emphasis"
                }
            })
            this.recordPoint = cloneDeep(this.recordPoint)
            console.log(this.recordPoint)
            // console.log(this.sourceSpaceInfo.originMapData.recordPoint)
        },
        goToEnterprisePermit() { // 企业许可证
            this.$router.push({
                path: '/archives',
                query: {
                  enterpriseId: this.EnterpriseInfoID,
                  xkz: 1
                }
            })
        },
        goToVideoMangement() { // 视频
            if(this.sourceSpaceInfo.originBaseInfo.videoUrl) {
                this.myVideoShow = true
            } else {
                this.$router.push({
                    path: '/video-data',
                    query: {
                    enterpriseId: this.EnterpriseInfoID
                    }
                })
            }
        },
        /**
         * @desc 查看异常督办
         */
        goToRCIMAbnormalSupervision() {
            this.$router.push({
                path: '/RCIM-abnormalSupervision',
                query: {
                  enterpriseId: this.EnterpriseInfoID
                }
            })
        },
        /**
         * @desc 查看源记录
         */
        goToSourceRecord() {
            this.$router.push({
                path: '/source-record',
                query: {
                  enterpriseId: this.EnterpriseInfoID
                }
            })
        },
        handleCloseMyVideoShow() {
            this.myVideoShow = false
        },
        handleChangeLeftShow() {
            this.leftShow = !this.leftShow
        },
        /**
         * @desc 控制左侧显示
         */
        changeLeftShow() {
            let width = window.innerWidth
            if (width < 1367) {
                this.leftShow = false
                this.leftButtonShow = true
            } else {
                this.leftShow = true
                this.leftButtonShow = false
            }
        },
        getLineType(){
			let typeStr = '';
			let formatRule = '';
			switch (this.types) {
				case '2':
					typeStr = 'hour';
					formatRule = 'YYYY-MM-DD HH'
					break;
				case '3':
					typeStr = 'day';
					formatRule = 'YYYY-MM-DD'
					break;
				default:
					typeStr = 'minute';
					formatRule = 'YYYY-MM-DD HH:mm'
			}
			return {
				typeStr,
				formatRule,
			};
		},
        /**
         * @desc 获取鱼骨图数据
         */
        getFishData(){
			return getStatus(this.listQuery).then(res => {
				if( res.data?.timeLine && (res.data?.timeLine instanceof Array) ){
					this.list = res.data?.timeLine.map(item => {
						item.from = item.form;
						return item
					})
				}else{
					this.list = []
                }
                // debugger
				this.chartData = this.parseData()
				return res;
			})
		},
        /**
         * @desc 格式化数据
         * @param {Number} typeIndex
         * @returns optionsData数据
         */
		parseData(typeIndex = 0){
            const {typeStr, formatRule} = this.getLineType()
			let len = 0;
			const optionsData = {
				data: [],
				xdata: [],
				efData: [],
				vmap: [],
				scaData:[],
			}
			const _self = this;
			optionsData.vmap = this.list.map( (item, index) => {

				let itemBtw = 1
				if(item.to){
					itemBtw = 20; //moment(item.to).diff(item.from, _self.dateUit)
				}
				console.log(itemBtw)
				let whileIndex = 1;
				optionsData.data.push(_self.getItemLineData('symbol'))
				optionsData.xdata.push(item.from)
				optionsData.scaData.push(_self.getScatterData('symbol', item.from))
				optionsData.efData.push(_self.getItemSymleData('symbol', item.status, index === typeIndex ? 'render': 'emphasis', index))
				for( ; whileIndex < itemBtw; whileIndex ++ ){
					optionsData.data.push(_self.getItemLineData())
					optionsData.xdata.push(moment(item.from).add(whileIndex, _self.dateUit).format(formatRule))
					optionsData.scaData.push(_self.getScatterData())
					optionsData.efData.push(_self.getItemSymleData())
				}
				const result = {
					gte: len,
					lt: len + itemBtw,
					color: _self.colorList[item.status],
				}
				len += itemBtw
				return result
			})
            console.log(optionsData)
			return optionsData
		},
        /**
         * @desc 获取折线图数据
         */
		getItemLineData(type){
			const itemLineSymbelData = {
				value: 1,
				symbol: 'none' ,
			}
			const itemData = {
				value: 1,
				symbol: 'none',
			}
			if(type === 'symbol') {
				console.log('====',itemLineSymbelData)
				return itemLineSymbelData
			}else{
				return itemData
			}
		},
        /**
         * @desc 获取离散数据
         */
		getScatterData(type, times){
			const itemSymbelData = {
				value: 1,
				times,
				symbolSize: 1,
			}
			const itemData = {
				value: 1,
				symbol: 'none',
			}
			if(type === 'symbol') {
				return itemSymbelData
			}else{
				return itemData
			}
		},
        /**
         * @desc 获取常规数据，方便调用
         * @param {String} type
         * @param {String} status
         * @param {String} rip
         * @param {Number} index
         */
		getItemSymleData(type, status, rip, index){
			const itemSymbelData = {
				value: 1,
				status,
				index,
				symbolSize: 12,
				showEffectOn: rip,
				itemStyle: {
					color: this.colorList[status],
					shadowBlur: 10,
					shadowColor: '#333',
					borderWidth: '10',
					boderColor: '#000'
				},
			}
			const itemData = {
				value: 1,
				symbol: 'none',
			}
			if(type === 'symbol') {
				return itemSymbelData
			}else{
				return itemData
			}
        },
        /**
         * 点击鱼骨图回调
         * @param {*} params 鱼骨图数据
         */
		clickFish(params){
			console.log('params',params)
			const _self = this;
            _self.selectId = this.list[params.index].statusId;
			this.handleChangeRecodeIdFish(_self.selectId)
        },
        /**
         * 修改时间回调
         * @param {*} value 时间数据
         */
        async changeDate(value){
            this.listQuery.startTime = moment(value[0]).format('YYYY-MM-DD HH:mm')
            this.listQuery.endTime = moment(value[1]).format('YYYY-MM-DD HH:mm')
			this.listQuery.id = this.useRadDeviceID;
			const _self = this;
			await this.getRadPath(this.listQuery)
			this.getFishData()
			.then(res => {
				_self.selectId = res.data.timeLine[0].statusId;
				// setTimeout(() => {
					this.handleChangeRecodeIdFish(_self.selectId)

				// },2000)
			})
        },
    },
}
